/**
 * WhiMAIcpp - C++ interface for the Whiskey Media APIs.
 *  Copyright (C) 2010  Anders Bugge
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "parser.h"

// STL
#include <sstream>
#ifdef WHIMAI_DEBUG
#include <iostream>
#endif

// json
#include "json\reader.h"

// VMA includes
#include "interface.h"

namespace WM
{

Parser::Parser()
{
	jObject = new json::Object();

	// Get access to the API interface
	interface = Interface::Instance();
	data = "";
	url = "";
}

Parser::~Parser()
{
	delete jObject;

	// Release access
	Interface::Release();
}

bool Parser::parseData()
{
	// clear old data
	jObject->Clear();

	// get the data string
	unsigned int error = interface->getData( data, url );

#ifdef WHIMAI_DEBUG
	std::cout << "REQUEST URL: " << url << std::endl;
	std::cout << "ERROR CODE: " << error << std::endl;
	std::cout << "RECEIVED DATA: " << data << std::endl;
#endif

	if( error )
		return false;

	// parse the data in to object
	try
	{
		std::stringstream ss;
		ss << data;
		json::Reader::Read( *jObject, ss );
	}
	catch( const json::Exception& e )
	{
#ifdef WHIMAI_DEBUG
		std::cout << "PARSER ERROR: " << e.what() << std::endl;
#endif
		return false;
	}

	// check for general errors
	try
	{
		const json::Number status_code = jObject->Find("status_code")->element;
		if( status_code != 1 )
		{
#ifdef WHIMAI_DEBUG
			const json::String error = jObject->Find("error")->element;
			std::cout << "API ERROR: " << status_code << "," << error.Value() << std::endl;
#endif
			return false;
		}
	}
	catch( const json::Exception& e )
	{
#ifdef WHIMAI_DEBUG
		std::cout << "PARSER ERROR: " << e.what() << std::endl;
#endif
		return false;
	}

	return true;
}

}
